using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

using System.Web.Security;
using System.Web;
using System.DirectoryServices;
using System.Security.Principal;
using System.Net.Mail;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.Configuration;
using System.Diagnostics;
using EAT.Common;

namespace EAT.ExternalCollaboration
{
    /*++
     class ProfilePage
     
     This class provides functionality for external users to modify their profile
     information.
    --*/

    public class ProfilePage : Microsoft.SharePoint.WebControls.LayoutsPageBase
    {
        protected EAT.Common.cUserManager UM;

        //
        // The following text boxes display information about the user
        // loaded (and saved to) ADAM.
        //
        protected System.Web.UI.WebControls.TextBox tbFirstName;
        protected System.Web.UI.WebControls.TextBox tbLastName;
        protected System.Web.UI.WebControls.TextBox tbCompanyName;
        protected System.Web.UI.WebControls.TextBox tbTelephoneNumber;
        protected System.Web.UI.WebControls.Label lblAccountName;

        //
        // This textbox recieves the user's password.  This is validated
        // to unlock further profile update options.
        //
        protected System.Web.UI.WebControls.TextBox tbPassword;

        //
        // Radio buttons to select password modification and secret q/a update.
        //
        protected System.Web.UI.WebControls.CheckBox cbChangePassword;
        protected System.Web.UI.WebControls.TextBox tbNewPassword;
        protected System.Web.UI.WebControls.TextBox tbConfirmPassword;

        protected System.Web.UI.WebControls.CheckBox cbChangeQA;
        protected System.Web.UI.WebControls.TextBox tbQuestion;
        protected System.Web.UI.WebControls.TextBox tbAnswer;

        protected System.Web.UI.WebControls.Label lblInternalCaller;
        //
        // Button to submit changes to ADAM.
        //
        protected System.Web.UI.WebControls.Button btnUpdate;
        protected System.Web.UI.WebControls.Label lblDebug;

        [DllImport("advapi32.dll", SetLastError = true)]
        static extern int RevertToSelf();


        private void InternalCaller()
        {
            tbFirstName.Enabled = false;
            tbLastName.Enabled = false;
            tbCompanyName.Enabled = false;
            tbTelephoneNumber.Enabled = false;

            tbPassword.Enabled = false;
            tbConfirmPassword.Enabled = false;
            tbNewPassword.Enabled = false;

            tbQuestion.Enabled = false;
            tbAnswer.Enabled = false;

            btnUpdate.Enabled = false;

            cbChangePassword.Enabled = false;
            cbChangeQA.Enabled = false;
            
            SPWeb web = SPContext.Current.Web;
            SPUser u = web.CurrentUser;
            string RedirectUrl = web.Url.ToString() + "/_layouts/userdisp.aspx?ID=" + u.ID;
            Response.Redirect(RedirectUrl);
        }

        public ProfilePage()
        {
            UM = new Common.cUserManager(
                                ConfigurationManager.ConnectionStrings["ADAMConnectionString"].ConnectionString
                                );

        }

        public void btnUpdate_Click(object sender, EventArgs e)
        {
            MembershipUser u = Membership.GetUser();
            bool bProfile = false;
            lblDebug.Text = "";

            try
            {
                //DirectoryEntry de = UM.FindUser(u.UserName);
                //de.Options.PasswordPort = UM.Connection.Port();

                if (cbChangeQA.Checked == true)
                {
                    cbChangeQA.Checked = false;
                    if (u.ChangePasswordQuestionAndAnswer(tbPassword.Text, tbQuestion.Text, tbAnswer.Text) == false)
                    {
                        lblDebug.Text += Resources.profileUpdateQAErrorText;
                    }
                    else
                    {
                        lblDebug.Text += Resources.profileUpdatedQAText + "<br>";
                    }
                }

                if (cbChangePassword.Checked == true)
                {
                    cbChangePassword.Checked = false;
                    
                    // this is somewhat redundant as the ChangePassword below will validate
                    // the user's password as well. This does provide a better error message,
                    // however, so I'm leaving it here.
                    if (Membership.ValidateUser(u.UserName, tbPassword.Text) == false)
                    {
                        throw new Exception(Resources.cqaWrongPasswordEnteredText);
                    }

                    if (tbNewPassword.Text != tbConfirmPassword.Text)
                    {
                        throw new Exception(Resources.profilePasswordsDoNotMatch);
                    }

                    try
                    {
                        UM.ChangePassword(u, tbPassword.Text, tbNewPassword.Text);
                        lblDebug.Text += Resources.profileUpdatedPasswordText + "<br>";
                    }
                    catch(System.Reflection.TargetInvocationException)
                    {
                        throw new Exception(Resources.passwordConstraintViolationText);
                    }
                }

                if (tbCompanyName.Text == "")
                {
                    throw new Exception(Resources.ECNoCompanyNameText);
                }
                if (tbFirstName.Text == "")
                {
                    throw new Exception(Resources.ECNoFirstNameText);
                }
                if (tbLastName.Text == "")
                {
                    throw new Exception(Resources.ECNoLastNameText);
                }
                if (tbTelephoneNumber.Text == "")
                {
                    throw new Exception(Resources.ECNoPhoneNumberText);
                }

                UM.SetProfileInformation(u, tbCompanyName.Text, tbFirstName.Text, tbLastName.Text, tbTelephoneNumber.Text);
                lblDebug.Text += Resources.profileUpdatedProfileText + "<br>";
            }
            catch (Exception Ex)
            {
                lblDebug.Text = Ex.Message;
            }
        }

        public void cbChangePassword_Click(object sender, EventArgs e)
        {
            if (cbChangePassword.Checked)
            {
                tbNewPassword.Enabled = true;
                tbConfirmPassword.Enabled = true;
            }
            else
            {
                tbNewPassword.Enabled = false;
                tbConfirmPassword.Enabled = false;
            }
        }

        public void cbChangeQA_Click(object sender, EventArgs e)
        {
            if (cbChangeQA.Checked)
            {
                tbQuestion.Enabled = true;
                tbAnswer.Enabled = true;
            }
            else
            {
                tbQuestion.Enabled = false;
                tbAnswer.Enabled = false;
            }
        }

        protected void Page_Load()
        {
            MembershipUser Mu;

            try
            {
                Mu = Membership.GetUser();
            }
            catch (Exception Ex)
            {
                InternalCaller();
                return;
            }

            if (Mu == null)
            {
                return;
            }

            lblAccountName.Text = String.Format(Resources.profileEmailAddressLabel, Mu.Email);

            if (!Page.IsPostBack)
            {
                tbCompanyName.Text = UM.GetUserAttribute(Mu, "company");
                tbFirstName.Text = UM.GetUserAttribute(Mu, "givenName");
                tbLastName.Text = UM.GetUserAttribute(Mu, "sn");
                tbTelephoneNumber.Text = UM.GetUserAttribute(Mu, "telephoneNumber");
                tbQuestion.Text = UM.GetUserAttribute(Mu, "eatmuPasswordQuestion");
                
                cbChangePassword.Enabled = true;
                cbChangePassword.Checked = false;

                cbChangeQA.Enabled = true;
                cbChangeQA.Checked = false;
            }
        }
    }
}